package com.kob.botrunningsystem.service.impl.utils;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class BotPool extends Thread{
    private  final ReentrantLock lock = new ReentrantLock();
    private  final Condition condition = lock.newCondition();
    private final Queue<Bot> bots=new LinkedList<Bot>();

    public void addBot(Integer userId,String botCode,String input) {
        lock.lock();
        try{
            bots.add(new Bot(userId,botCode,input));
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    private void consume(Bot bot){
        Consumer consumer = new Consumer();
        consumer.startTimeout(2000,bot);//最多执行2s
    }

    @Override
    public void run() {
        while(true){
            lock.lock();
            if(bots.isEmpty()){
                try {
                    condition.await();//先执行到这里进入睡入状态，在执行condition.signalAll
                }catch(InterruptedException e){
                    e.printStackTrace();
                    lock.unlock();
                    break;
                }
            }else{
                Bot bot=bots.remove();//取出队头
                lock.unlock();
                consume(bot);
            }
        }
    }
}
